// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { page = 1, pageSize = 10 } = event
  
  try {
    // 获取用户游戏历史记录
    const history = await db.collection('gameRecords')
      .where({
        players: wxContext.OPENID
      })
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()
    
    // 获取总记录数
    const count = await db.collection('gameRecords')
      .where({
        players: wxContext.OPENID
      })
      .count()
    
    // 获取玩家信息
    const playerIds = new Set()
    history.data.forEach(record => {
      record.players.forEach(player => {
        playerIds.add(player.openid)
      })
    })
    
    const players = await db.collection('users')
      .where({
        _openid: db.command.in([...playerIds])
      })
      .get()
    
    const playerMap = {}
    players.data.forEach(player => {
      playerMap[player._openid] = player
    })
    
    // 处理历史记录数据
    const processedHistory = history.data.map(record => {
      return {
        ...record,
        players: record.players.map(player => ({
          ...player,
          nickName: playerMap[player.openid]?.nickName || '未知用户',
          avatarUrl: playerMap[player.openid]?.avatarUrl || ''
        }))
      }
    })
    
    return {
      success: true,
      data: {
        records: processedHistory,
        total: count.total,
        page,
        pageSize
      }
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 